<?php


namespace app\controller;


use app\BaseController;
use app\common\constants\ReturnCodeConstants;
use app\common\exception\HttpRequestException;
use app\common\util\HttpRequest;
use app\common\util\Response;
use think\response\Json;

class HttpRequestExample extends BaseController
{
    public function example(): Json
    {
        //请求头,如果要加的话
        $headers = [];
        //请求地址
        $url = 'http://www.baidu.com.cn?test=1';
        $client = new HttpRequest($headers);

        /**
         * 可配置可不配置
         */
        //设置请求超时时间
        $client->setTimeout(3);
        //是否校验返回参数
        $client->setIsVerifyException(true);
        //设置请求头
        $client->setHeaders(['Accept-Encoding' => 'gzip']);
        //设置是否校验ssl证书
        $client->setIsVerifySsl(false);
        //设置返回的数据格式，默认code,msg,data
        $client->setResponseFormat('code', 'message', 'data');
        //设置请求成功的状态码
        $client->setResponseSuccessCode(0);

        try {
            $params = ['test2' => 2];

            //get请求
            $data = $client->get($url, $params);
            //post请求
            $data = $client->post($url, $params);
            //put请求
            $data = $client->put($url, $params);
            //delete请求
            $data = $client->delete($url, $params);

            return Response::successJson($data);
        } catch (HttpRequestException $e) {
            return Response::failureJson(ReturnCodeConstants::DEFAULT_ERROR_CODE, $e->getMessage());
        }
    }
}